package com.example.ll_video.utils;

import android.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ThreeDESUtils {

    // 向量 可有可无 终端后台也要约定
    private final static String iv = "androidandios";
    // 密钥 长度不得小于24
    private final static String secretKey = MD5.getStringMD5("AndroidandIOS");
    // 加解密统一使用的编码方式
    private final static String encoding = "UTF-8";

    /**
     * 3DES加密
     *
     * @param plainText
     *            普通文本
     * @return
     * @throws
     */
    public static String encode(String plainText) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] encryptData = cipher.doFinal( plainText.getBytes( encoding));
        return Base64.encodeToString(encryptData,Base64.DEFAULT);
    }

    /**
     * 3DES解密
     *
     * @param encryptText
     *            加密文本
     * @return
     * @throws
     */
    public static String decode(String encryptText) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec( secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "desede");
        deskey = keyfactory.generateSecret( spec);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, deskey);

        byte[] decryptData = cipher.doFinal(Base64.decode(encryptText,Base64.DEFAULT));

        return new String( decryptData, encoding);
    }

    public static void main(String args[]) throws Exception{
        String str = "1599" ;
        System.out.println( "----加密前-----：" + str );
        String encodeStr = encode( str);
        System.out.println( "----加密后-----：" + encodeStr );
        System.out.println( "----解密后-----：" + decode( encodeStr));
        System.out.println( "----解密后老王-----：" + decode("StpI1Dfu4gU="));


    }
}
